import 'dart:io';

import 'package:dio/dio.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/user_edit_request.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/appbar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';
// import 'package:image_picker/image_picker.dart';


class PerfectInformationPage extends StatefulWidget {
  const PerfectInformationPage({Key key}) : super(key: key);

  @override
  _RegistarPageState createState() => _RegistarPageState();
}

class _RegistarPageState extends State<PerfectInformationPage> {
  var _imagePath ;
  ///记录每次选择的图片
  List<File> _images = [];
//  List<PickedFile> _images = [];
  TextEditingController controller = TextEditingController();
  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    var image;
    try {
          image = await ImagePicker.pickImage(
          source:isTakePhoto ? ImageSource.camera :ImageSource.gallery
      );
      if (image == null) {
        return;
      } else {
        setState(() {
          // _image = image;
          _images.add(image);
        });
      }
    } catch (e) {
      print("模拟器不支持相机！");
    }
  }
  // final picker = ImagePicker();
  bool boySex = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3c),
      appBar: AppBar(
        actions: [
          Padding(padding: EdgeInsets.only(right: SizeUtil.px(44)),
            child: InkWell(
              onTap: (){
                Navigator.pop(context);
              },
              child: Center(
                child: Text(
                  '跳过',style: TextStyle(fontSize: SizeUtil.px(28),color: Color(0xfff3f3f3)),
                ),
              ),
            ),
          )
        ],
        leading: new IconButton(
            onPressed: () {
              Navigator.pushNamed(context, '/index');
            },
            icon: Icon(Icons.arrow_back_ios)),
        title: Text("创建个人资料"),
        centerTitle: true,
        backgroundColor: Color(0xff140c3c),
      ),
      body:SingleChildScrollView(
        child: Container(
          child: Column(
            children: [
              Padding(
                  padding: EdgeInsets.only(top: 21),
                  child: Center(
                    child: Text(
                      '欢迎来到象鱼~',
                      style: TextStyle(
                        fontSize: 22.5,
                        color: Color(0xfff3f3f3),
                      ),
                    ),
                  )),
              Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: Center(
                    child: Text(
                      '为你发现更契合的TA',
                      style: TextStyle(
                        fontSize: 12.5,
                        color: Color(0xffd5d5d5),
                      ),
                    ),
                  )),
              Padding(
                  padding: EdgeInsets.only(top: 14),
                  child: InkWell(
                    child: Center(
                        child: Container(
                          //加载网络图片
                          height: 70.0,
                          width: 70.0,
                          decoration: BoxDecoration(
                            color: Color(0xffd5d5d5),
                            borderRadius: BorderRadius.all(
                              Radius.circular(150),
                            ),
                          ),
                          child:  Wrap(
                            spacing: 5,
                            runSpacing: 5,
                            children: _generateImages(),
                          ),
                        )),
                    onTap: () async {
                      // var image = picker.getImage(source: ImageSource.gallery);
                      _pickImage();

                        // _imagePath = image;
                    },
                  ),
              ),
              Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: Center(
                    child: Text(
                      '完善信息，可以加到更多好友哦',
                      style: TextStyle(
                        fontSize: 11,
                        color: Color(0xffd5d5d5),
                      ),
                    ),
                  )),
              Padding(
                  padding: EdgeInsets.only(top: 66.5),
                  child: Center(
                      child: TextField(
                        controller: controller,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontSize: 13,
                              color: Color(0xffd5d5d5),
                              fontWeight: FontWeight.bold),
                          //输入框的样式
                          decoration: InputDecoration(
                            contentPadding:
                            EdgeInsets.only(left: 155, right: 155),
                            border: InputBorder.none,
                            hintText: '取个名字吧',
                            hintStyle: TextStyle(
                              fontSize: 13,
                              color: Color(0xffd5d5d5),
                            ),
                          )))),
              Padding(
                  padding: EdgeInsets.only(top: 7),
                  child: Center(
                      child: Divider(
                        height: 1.0,
                        indent: 98.5,
                        endIndent: 97,
                        color: Color(0xff707070),
                      )
                  )),
              Padding(
                  padding: EdgeInsets.only(top: 110),
                  child: Center(
                    child: Text(
                      '请选择性别',
                      style: TextStyle(
                        fontSize: 15.5,
                        fontWeight: FontWeight.bold,
                        color: Color(0xfff3f3f3),
                      ),
                    ),
                  )),
              Padding(
                  padding: EdgeInsets.only(left:91.5,right:90,top: 23.5),
                  child: Row(
                    children: [
                      Container(
                        height: 70.0,
                        width: 70.0,
                        decoration: BoxDecoration(
                          // color: Colors.yellow,
                            borderRadius: BorderRadius.all(
                              Radius.circular(150),
                            ),
                            image: DecorationImage(
                              image: boySex ? AssetImage('assets/images/boy_checked.png') : AssetImage('assets/images/boy_unchecked.png'),
                              fit: BoxFit.cover,
                            )),
                        child: InkWell(
                          onTap: (){
                            setState(() {
                              boySex = true;
                            });
                          },
                        ),
                      ),
                      Spacer(),
                      Container(
                          height: 70.0,
                          width: 70.0,
                          decoration: BoxDecoration(
                            // color: Colors.yellow,
                              borderRadius: BorderRadius.all(
                                Radius.circular(150),
                              ),
                              image: DecorationImage(
                                image:  boySex ? AssetImage('assets/images/girl_unchecked.png') : AssetImage('assets/images/girl_checked.png'),
                                fit: BoxFit.cover,
                              )),
                          child: InkWell(
                            onTap: (){
                              setState(() {
                                boySex = false;
                              });
                            },
                          )

                      ),
                    ],
                  )),
              SizedBox(height: SizeUtil.px(128),),
              InkWell(
                child:
                Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                    width: SizeUtil.px(650),
                    height: SizeUtil.px(91),
                    decoration: BoxDecoration(
                      color: Color(0xffe62d6c),
                      borderRadius: BorderRadius.all(Radius.circular(SizeUtil.px(46))),
                    ),
                    child: Center(
                      child: Text(
                        '下一步',style: TextStyle(fontSize: SizeUtil.px(32),color: Color(0xfff9f9f9)),
                      ),
                    ),
                  ),
                ),
                onTap: (){
                  perfectUserInfo();
                },
              )
            ],
          ),
        ),
      ),

    );
  }

   Widget _ImageView(imagePath) {
    if(imagePath == null){
      return Icon(Icons.add,size: SizeUtil.px(70),color: Color(0xfff3f3f3),);
    }else{
      return Image.file(imagePath);
    }
  }

  ///底部弹框
  _pickImage() {
    showModalBottomSheet(context: context, builder: (context) =>
        Container(
          height: 160,
          child: Column(
            children: <Widget>[
              _takePhotoItem('拍照', true),
              _takePhotoItem('从相册选择', false),
            ],
          ),
        ));
  }
  _takePhotoItem(String title, bool isTakePhoto) {
    print(isTakePhoto);
    return GestureDetector(
      child: ListTile(
        leading: Icon(
          isTakePhoto ? Icons.camera_alt : Icons.photo_library,
        ),
        title: Text(title),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }

  /// 封装图片面板
  _generateImages() {
    return _images.map((file){
      return Stack(
        children: <Widget>[
          ClipRRect(
            //圆角效果
            borderRadius: BorderRadius.circular(SizeUtil.px(70)),
            child: Image.file(file,width: SizeUtil.px(140),height: SizeUtil.px(140),fit:BoxFit.fill),
          ),
          Positioned(
            right: 5,
            top: 5,
            child: GestureDetector(
              onTap: (){
                setState(() {
                  _images.remove(file);
                });
              },
              child: ClipOval(
                //圆角删除按钮
                child: Container(
                  padding: EdgeInsets.all(5),
                  decoration: BoxDecoration(color: Colors.black54),
                  child: Icon(Icons.close,size: 20,color: Colors.white,),
                ),
              ),
            ),
          ),
        ],
      );
    }).toList();
  }
  
  perfectUserInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    int sex;
    if(boySex){
      sex = 2;
    }else{
      sex = 1;
    }
    if(controller.text == '' || _images[0] == null){
      TxUtils.showToast('数据填写不完整', context);
    }else{
      FormData formData = FormData.fromMap({
        'nickname': controller.text,
        'avatar': await MultipartFile.fromFile(_images[0].path),
        'sex': sex,
      });
      var dio = new Dio();
      dio.options.headers = {"usertoken": appToken};
      var response ;
      try{
        response = await dio.post("http://119.28.131.94:82/app/user/edit", data: formData);
        var result = response.data;
        if (result['code'] == -1) {
          TxUtils.showErrorToast('登录失效，请重新登录', context);
          Navigator.pop(context);
          Navigator.of(context).push(MaterialPageRoute(
            builder: (context) {
              return LoginPage(
                arguments: {'loginCode': '-1'},
              );
            },
          ));
        } else if (result['code'] == 413) {
          TxUtils.showErrorToast('文件太大，无法上传', context);
        } else {
          TxUtils.showToast(result['data'], context);
          Navigator.pushNamed(context, '/index');
        }
      }catch(e){
        print(e);
        if(e.response.statusCode == 413){
          TxUtils.showErrorToast('文件太大，无法上传', context);
        }
      }
    }


  }

}
